<template>
  <img
    v-if="!src"
    ref="target"
    v-bind="eager ? null : { loading: 'lazy' }"
    :width="withoutPx(width) || 'auto'"
    :height="withoutPx(height) || 'auto'"
    :title="alt || 'How to recharge game and live streaming products'"
    :src="useAsset('1x1.jpg')"
    :alt="alt || 'How to recharge game and live streaming products'" />
  <img
    v-else
    v-bind="eager ? null : { loading: 'lazy' }"
    class="object-cover"
    ref="target"
    :width="withoutPx(width) || 'auto'"
    :height="withoutPx(height) || 'auto'"
    :src="realImageUri"
    :title="alt || 'How to recharge game and live streaming products'"
    :alt="alt || 'How to recharge game and live streaming products'" />
</template>

<script setup lang="ts">
const props = defineProps<{
  width?: string | number
  height?: string | number
  lazy?: boolean
  eager?: boolean
  placeholder?: boolean
  compress?: boolean
  alt?: string
  src: any
  fit?: string
}>()
// 由于服务端渲染拿不到dpr 所以统一给2倍图了
const dpr = 2
const target = ref<HTMLImageElement>()
const withoutPx = (str: any) => +(typeof str === 'string' ? str.replace('px', '') : str) || undefined
const img = useImage()
const { IS_PROD, IMAGE_DOMAIN } = useRuntimeConfig().public
const IMAGE_SRC = computed(() => {
  if (props.src?.startsWith('http')) return props.src
  if (!props.src) return ''
  return `${IS_PROD ? IMAGE_DOMAIN : ''}/v2/${props.src}`
})

const realImageUri = computed(() => {
  const w = withoutPx(props.width),
    h = withoutPx(props.height)
  return (
    IMAGE_SRC.value &&
    img(
      IMAGE_SRC.value,
      {
        width: w && Math.round(w * dpr),
        height: h && Math.round(h * dpr),
        format: 'webp',
        fit: props.fit || undefined,
        compress: props.compress,
      },
      {
        provider: 'myProvider',
      },
    )
  )
})
</script>

<style lang="scss"></style>
